package com.chushouya.manager.service.api.impl;


import com.chushouya.common.support.Contexts;
import com.chushouya.common.support.RequestHeaderContext;
import com.chushouya.common.support.RequestUserContext;
import com.general.framework.core.lang.Longs;
import com.chushouya.manager.constants.UserStatusEnum;
import com.chushouya.manager.dao.entity.PartnerEntity;
import com.chushouya.manager.dao.entity.UserEntity;
import com.chushouya.manager.dao.entity.UserExtendEntity;
import com.chushouya.manager.dao.repository.PartnerRepository;
import com.chushouya.manager.dao.repository.UserExtendRepository;
import com.chushouya.manager.dao.repository.UserRepository;
import com.chushouya.manager.dto.admin.user.login.UserCenterDTO;
import com.chushouya.manager.dto.admin.user.query.UserQuery;
import com.chushouya.manager.service.api.UserApiService;
import com.chushouya.manager.service.api.UserExtendService;
import com.chushouya.manager.service.api.WebAppTokenService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.lang.Validate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class UserApiServiceImpl implements UserApiService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserExtendRepository userExtendRepository;

    @Resource
    private UserExtendService userExtendService;

    @Resource
    private WebAppTokenService webAppTokenService;

    @Resource
    private PartnerRepository partnerRepository;

    private PartnerEntity getPartnerInfo(Long partnerId){
        if (Longs.isNullOrZero(partnerId)) {
//            throw Ex.business("商户ID不能为空");
            partnerId = 100004L;
        }
        final Long partnerIdLong = Long.valueOf(partnerId);
        PartnerEntity partnerEntity = partnerRepository.selectByPrimaryKey(partnerIdLong);
        if (Objects.isNull(partnerEntity)) {
            throw Ex.business("商户不存在");
        }
        if (!Objects.equals(partnerEntity.getStatus(), 1)) {
            throw Ex.business("商户不可用");
        }
        return partnerEntity;
    }

    @Override
    public UserEntity selectByUserName(String userName) {
        UserQuery query = new UserQuery();
        query.setUserPhone(userName);
        query.setStatus(UserStatusEnum.NORMAL.value());
        return userRepository.selectOne(query);
    }

    @Override
    public UserEntity selectByUserId(Long userId) {
        UserQuery query = new UserQuery();
        query.setUserId(userId);
        query.setStatus(UserStatusEnum.NORMAL.value());
        return userRepository.selectOne(query);
    }

    @Override
    public UserEntity register(Integer userType, String userName, String userPhone) {
        final Date timeNow = Dates.getTimeNow();
        final Long partnerId = Contexts.getHeaderContext().getPartnerId();
        log.info("用户注册，用户名：{}，手机号：{}", partnerId, Contexts.getHeaderContext());
        final PartnerEntity partnerEntity = getPartnerInfo(partnerId);
        Validate.isBlank(userName, "用户名不能为空");
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(userName);
        userEntity.setUserPhone(userPhone);
        userEntity.setUserType(userType);
        userEntity.setPartnerId(partnerEntity.getPartnerId());
        userEntity.setPartnerName(partnerEntity.getPartnerName());
        userEntity.setUpdateTime(timeNow);
        userEntity.setCreateTime(timeNow);
        userEntity.setStatus(UserStatusEnum.NORMAL.value());
        try {
            userRepository.insertSelective(userEntity);
        } catch (RuntimeException e) {
            log.error("用户注册异常", e);
            throw Ex.business("服务器繁忙，请稍后重试");
        }
        return userEntity;
    }

    @Override
    public void update(UserEntity userEntity) {
        Validate.isTrue(userEntity == null || userEntity.getUserId() == null, "用户不存在");
        userRepository.updateByPrimaryKeySelective(userEntity);
    }

    @Override
    public UserCenterDTO userCenter() {

        RequestUserContext userContext = Contexts.getUserContext();
        RequestHeaderContext headerContext = Contexts.getHeaderContext();
        UserCenterDTO userCenterDTO = new UserCenterDTO();

        //头像， 昵称
        UserExtendEntity userExtend = userExtendService.selectByAppIdAndUserId(headerContext.getAppId(),userContext.getUserId());
        if (userExtend != null) {
            userCenterDTO.setNickName(userExtend.getNickName());
            userCenterDTO.setAvatar(userExtend.getAvatar());
        } else {
            userCenterDTO.setNickName("");
            userCenterDTO.setAvatar("");
        }
        //用户名
        UserEntity userEntity = selectByUserId(userContext.getUserId());
        Validate.isNull(userEntity, "用户不存在");
        userCenterDTO.setUserName(userEntity.getUserName());
        userCenterDTO.setPhone(userEntity.getUserPhone());
        userCenterDTO.setUserId(userEntity.getUserId());
        //加价券数量
        userCenterDTO.setCouponNum(0L);
        return userCenterDTO;
    }

    @Override
    public void close() {
        log.info("用户退出登录");
        Long userId = Contexts.getUserContext().getUserId();
        UserEntity userEntity = selectByUserId(userId);
        Validate.isNull(userEntity, "用户不存在");

        UserEntity update = new UserEntity();
        update.setUserId(userId);
        update.setUpdateTime(Dates.getTimeNow());
        update.setUserPhone(Strings.format("{}-{}", userEntity.getUserPhone(), new Date().getTime()));
        update.setUserName(Strings.format("用户已注销{}",new Date().getTime()));
        update.setStatus(UserStatusEnum.CANCEL.value());
        userRepository.updateByPrimaryKeySelective(update);

        List<UserExtendEntity> userExtendList = userExtendRepository.selectListByUserId(userId);
        for (UserExtendEntity userExtendEntity : userExtendList) {
            UserExtendEntity updateExtend = new UserExtendEntity();
            updateExtend.setUserExtendId(userExtendEntity.getUserExtendId());
            updateExtend.setUpdateTime(Dates.getTimeNow());
            updateExtend.setDelFlag(1);
            userExtendRepository.updateByPrimaryKeySelective(updateExtend);
        }
        webAppTokenService.delLoginToken(userId);
    }

    @Override
    public void logout() {


    }

    @Override
    public void changeUserType(Long userId, Integer userType) {
        UserEntity update = new UserEntity();
        update.setUserId(userId);
        update.setUserType(userType);
        update.setStatus(UserStatusEnum.NORMAL.value());
        update.setUpdateTime(Dates.getTimeNow());
        userRepository.updateByPrimaryKeySelective(update);
    }

}
